<?php
class Categories extends MY_Controller{
	//前置过滤
	var $beforeFilter = array(
			'initAdmin' => array(
				'only' => array('admin','add','remove','edit'),
			),
		);

	function Categories()
	{
		parent::MY_Controller();
		$this->load->helper(array('url','system'));
		$this->load->model('ArticleCat');
	}
	
	function index()
	{	
		$this->assign['result'] = $this->listAll();
		$this->display();
	}

	function getGlist()
	{	
		$this->assign['result'] = $this->gList();
		$this->display();
	}
	
	function admin(){
		$type=$_GET['type'];
		if($type=='good'){
			$this->assign['categories'] = $this->gList();
		}else{
			$this->assign['categories'] = $this->listAll();
		}
		$this->display();
	}

	function listAll(){
		$res = $this->ArticleCat->doList();
		$res = cat_options(0, $res);
		return $res;
	}
	
	function gList(){
		$res = $this->ArticleCat->doList();
		$res = cat_options(2, $res);
		return $res;
	}
	function save(){
		$redirect = $this->getRedirect('category_admin');
		$rules = array(
			'name' => 'trim|required',
		);
		if ($this->validation($rules) == FALSE)
		{
			$this->showMessage('error_wrong_input'); 
		}
		$config['upload_path'] = "./data/uploads/files/";
        $this->load->library('upload', $config);
        $name = explode('.',$_FILES['userfile']['name']);
        $type = $name[count($name)-1];
        if(!$this->upload->do_upload()) {
            echo $this->upload->display_errors();
        }
        if(empty($_POST['userfile'])){
        	 $_POST['file_url'] = "data/uploads/files/".$this->upload->do_upload();
        }else{
        	$_POST['file_url'] = $_POST['userfile'];
        }
		if(empty($_POST['cat_desc']))$_POST['cat_desc'] = $_POST['name'];
		if(empty($_POST['keywords']))$_POST['keywords'] = $_POST['name'];
		$this->ArticleCat->save($_POST);
		$this->showMessage('mes_success',$redirect);
	}

	function doEdit($id=null){
		$this->load->helper('system');
		$this->load->helper('form');
		$redirect = $this->getRedirect('category_admin');
		$result = $this->ArticleCat->doList();
		if($id>0){
			$cate  = getByCond($result,array('id'=>$id));
			$cate  = $cate[0];
			$this->assign['result'] = $cate;
		}
		$options = cat_list(cat_options(0, $result),0, $cate['parent_id'],false, 3,true);
		$this->assign['options'] = $options;
		$this->assign['redirect'] = $redirect;
		$this->template = 'categories_save';
		$this->display();
	}

	function add(){
		$this->doEdit();
	}

	function edit($id){
		$this->doEdit($id);
	}
	
	function remove($id=null){
		$redirect = $this->getRedirect('/index.php/categories/admin');
		$id = empty($id) ? $_REQUEST['id'] : $id;
		$this->ArticleCat->removeByPks($id);
		$this->showMessage('mes_success',$redirect);
	}
}